using UnityEngine;
using XLua;
using System;
using System.Collections.Generic;

public class LuaMgr : MonoBehaviour
{

    public static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
    internal static float lastGCTime = 0;
    internal const float GCInterval = 1;//1 second 

    private Action luaStart;
    private Action luaUpdate;
    private Action luaOnDestroy;
    private Action luaOnEnable;
    private Action luaOnDisable;
    private Action luaFixedUpdate;

    private LuaTable scriptEnv;

    public void Launch()
    {
        InitLoader();


        luaEnv.DoString("require 'main'");

        scriptEnv = luaEnv.Global;

        Action luaAwake = scriptEnv.Get<Action>("Awake");
        scriptEnv.Get("Start", out luaStart);
        scriptEnv.Get("Update", out luaUpdate);
        scriptEnv.Get("OnDestroy", out luaOnDestroy);
        scriptEnv.Get("OnEnable", out luaOnEnable);
        scriptEnv.Get("OnDisable", out luaOnDisable);
        scriptEnv.Get("FixedUpdate", out luaFixedUpdate);

        if (luaAwake != null)
        {
            luaAwake();
        }
        Debug.Log("LuaMgr Launch");
    }

    void Awake()
    {
        Launch();
    }

    // Use this for initialization
    void Start()
    {
        if (luaStart != null)
        {
            luaStart();
        }
    }

    private void OnEnable()
    {
        luaOnEnable();
    }

    private void OnDisable()
    {
        luaOnDisable();
    }

    // Update is called once per frame
    void Update()
    {
        if (luaUpdate != null)
        {
            luaUpdate();
        }
        if (Time.time - lastGCTime > GCInterval)
        {
            luaEnv.Tick();
            lastGCTime = Time.time;
        }
    }

    private void FixedUpdate()
    {
        luaFixedUpdate();
    }
    void OnDestroy()
    {
        if (luaOnDestroy != null)
        {
            luaOnDestroy();
        }
        luaOnDestroy = null;
        luaUpdate = null;
        luaStart = null;
        scriptEnv.Dispose();
    }

    private void InitLoader()
    {
        luaEnv.AddLoader(CustomLoader);
    }

    private byte[] CustomLoader(ref string filepath) {
        byte[] ret;
        if(path2bytes.TryGetValue(filepath, out ret))
        {
            return ret;
        }
        else
        {
            Debug.LogError("Can not load lua:" + filepath);
        }

        return ret;
    }

    public static Dictionary<string, byte[]> path2bytes;
}
